<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card >
            <el-alert show-icon type="warning" title="注意：只允许为第三级分类设置相关参数！" :closable="false"></el-alert>
            <el-row class="cat_opt">
                <el-col>
                    <span>选择商品分类：</span>
                    <el-cascader
                        v-model="selectedKeys"
                        expand-trigger="hover"
                        :options="cateList"
                        clearable
                        change-on-select
                        :props="cascaderProps"
                        @change="handleChange" style="width:500px;"></el-cascader>
                    <el-tabs v-model="activeName" @tab-click="handleTabClick">
                        <el-tab-pane label="动态参数" name="many">
                            <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="showDialog">添加参数</el-button>
                            <el-table :data="manyTableData" border stripe>
                                <el-table-column type="expand">
                                    <template slot-scope="scope">
                                        <el-tag closable v-for="(item,index) in scope.row.attr_vals" :key="index" @close="handleClose(index,scope)">{{ item }}</el-tag>
                                        <el-input
                                            class="input-new-tag"
                                            v-if="scope.row.inputVisible"
                                            v-model="scope.row.inputValue"
                                            ref="saveTagInput"
                                            size="small"
                                            @keyup.enter.native="handleInputConfirm(scope)"
                                            @blur="handleInputConfirm(scope)"
                                            >
                                            </el-input>
                                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope)">+ New Tag</el-button>
                                    </template>
                                </el-table-column>
                                <el-table-column type="index"></el-table-column>
                                <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                                <el-table-column label="操作">
                                    <template slot-scope="scope">
                                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="editAttr(scope)">编辑</el-button>
                                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteAttr(scope)">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                        <el-tab-pane label="静态属性" name="only">
                            <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="showDialog">添加属性</el-button>
                            <el-table :data="onlyTableData" border stripe>
                                <el-table-column type="expand">
                                    <template slot-scope="scope">
                                        <el-tag closable v-for="(item,index) in scope.row.attr_vals" :key="index" @close="handleClose(index,scope)">{{ item }}</el-tag>
                                        <el-input
                                            class="input-new-tag"
                                            v-if="scope.row.inputVisible"
                                            v-model="scope.row.inputValue"
                                            ref="saveTagInput"
                                            size="small"
                                            @keyup.enter.native="handleInputConfirm(scope)"
                                            @blur="handleInputConfirm(scope)"
                                            >
                                            </el-input>
                                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope)">+ New Tag</el-button>
                                    </template>
                                </el-table-column>
                                <el-table-column type="index"></el-table-column>
                                <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                                <el-table-column label="操作">
                                    <template slot-scope="scope">
                                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="editAttr(scope)">编辑</el-button>
                                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteAttr(scope)">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                    </el-tabs>
                </el-col>
            </el-row>
        </el-card>
        <el-dialog
            :title="'添加'+titleText"
            :visible.sync="addAttrDialogVisible"
            @closed="closedDialog"
            width="50%">
            <el-form :model="addAttrForm" :rules="addAttrRules" ref="addAttrRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addAttrForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addAttrDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addAttr">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog
            :title="'编辑'+titleText"
            :visible.sync="editAttrDialogVisible"
            @closed="closedEditDialog"
            width="50%">
            <el-form :model="editAttrForm" :rules="editAttrRules" ref="editAttrRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editAttrForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editAttrDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editAttrSubmit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data(){
        return{
            cateList:[],
            selectedKeys:[],
            cascaderProps:{ 
                expandTrigger: 'hover',
                value:'cat_id',
                label:'cat_name',
                children:'children'
            },
            activeName:'many',
            manyTableData:[],
            onlyTableData:[],
            addAttrDialogVisible:false,
            addAttrForm:{
                attr_name:''
            },
            addAttrRules:{
                attr_name:[
                    {
                        required:true,
                        message:'输入参数名称',
                        trriger:'blur'
                    }
                ]
            },
            editAttrDialogVisible:false,
            editAttrForm:{
                attr_name:''
            },
            editAttrRules:{
                attr_name:[
                    {
                        required:true,
                        message:'输入参数名称',
                        trriger:'blur'
                    }
                ]
            }
        }
    },
    created(){
        this.getCateList()
    },
    computed:{
        isBtnDisabled(){
            if(this.selectedKeys.length != 3){
                return true;
            }else{
                return false;
            }
        },
        catId(){
            if(this.selectedKeys.length == 3){
                return this.selectedKeys[2];
            }else{
                return null;
            }
        },
        titleText(){
            if(this.activeName == 'many'){
                return '动态参数';
            }else{
                return '静态属性';
            }
        }
    },
    methods:{
        async getCateList(){
            const {data:res} = await this.$http.get('categories')
            if(res.meta.status == 200){
                console.log(res.data);
                this.cateList = res.data;
                this.$message.success(res.meta.msg)
            }else{
                this.$message.error(res.meta.msg)
            }
        },
        async handleChange(){
            if(this.selectedKeys.length !== 3){
                this.selectedKeys = [];
                this.manyTableData = [];
                this.onlyTableData = [];
                return;
            }
            // 证明选中的是三级分类
            console.log(this.selectedKeys);
            const {data:res} = await this.$http.get(`categories/${this.catId}/attributes`,{params:{
                sel:this.activeName
            }})
            if(res.meta.status == 200){
                this.$message.success(res.meta.msg);
                console.log(res.data);
                res.data.forEach(item=>{
                    item.attr_vals = item.attr_vals ? item.attr_vals.split(' '):[];
                    item.inputVisible = false;
                    item.inputValue = '';
                })
                if(this.activeName == 'many'){
                    this.manyTableData = res.data;
                }else{
                    this.onlyTableData = res.data;
                }
            }else{
                this.$message.error(res.meta.msg);
            }
        },
        handleTabClick(){
            console.log(this.activeName);
            this.handleChange();
        },
        async editAttr(scope){
            // this.editAttrForm.attr_name = scope.row.attr_name
            const {data:res} = await this.$http.get(`categories/${this.catId}/attributes/${scope.row.attr_id}`,{
                params:{
                    attr_sel:this.activeName
                }
            });
            if(res.meta.status == 200){
                this.$message.success(res.meta.msg)
                this.editAttrForm = res.data
            }else{
                this.$message.error(res.meta.msg)
            }
            this.editAttrDialogVisible = true;
        },
        editAttrSubmit(){
            this.$refs.editAttrRef.validate(async valid=>{
                if(valid){
                    const {data:res} = await this.$http.put(`categories/${this.catId}/attributes/${this.editAttrForm.attr_id}`,{
                        attr_name:this.editAttrForm.attr_name,
                        attr_sel:this.activeName
                    })
                    if(res.meta.status == 200){
                        this.$message.success(res.meta.msg)
                    }else{
                        this.$message.error(res.meta.msg)
                    }
                    this.editAttrDialogVisible = false;
                    this.handleChange();
                }else{
                    this.$message.error('属性校验失败')
                }
                
            })
        },
        showDialog(){
            this.addAttrDialogVisible = true;
        },
        closedDialog(){
            this.$refs.addAttrRef.resetFields();
            this.addAttrDialogVisible = false;
        },
        closedEditDialog(){
            this.$refs.editAttrRef.resetFields();
            this.editAttrDialogVisible = false;
        },
        addAttr(){
            this.$refs.addAttrRef.validate(async valid=>{
                if(valid){
                    const {data:res} = await this.$http.post(`categories/${this.catId}/attributes`,{
                        attr_name:this.addAttrForm.attr_name,
                        attr_sel:this.activeName
                    })
                    if(res.meta.status == 201){
                        this.$message.success(res.meta.msg)
                    }else{
                        this.$message.error(res.meta.msg)
                    }
                    this.addAttrDialogVisible = false;
                    this.handleChange();
                }
            })
        },
        async deleteAttr(scope){
            const result = await this.$confirm('此操作将永久删除该数据，是否继续？','提示',{
                confirmButtonText:'确定',
                cancelButtonText:'取消',
                type:'warning'
            }).catch(err => err)
            if(result=='confirm'){
                const {data:res} = await this.$http.delete(`categories/${this.catId}/attributes/${scope.row.attr_id}`);
                if(res.meta.status == 200){
                    this.$message.success(res.meta.msg)
                    this.handleChange();
                }else{
                    this.$message.error(res.meta.msg)
                }
            }else{
                this.$message.info('取消删除')
            }
        },
        async handleInputConfirm(scope){
            // console.log('ok');
            // console.log(scope.row.inputValue);
            scope.row.inputValue = scope.row.inputValue.trim();
            scope.row.inputVisible = false;
            if(scope.row.inputValue){
                console.log('[]'+scope.row.inputValue);
                scope.row.attr_vals.push(scope.row.inputValue)
                scope.row.inputValue = '';
                scope.row.inputVisible = false;
                this.saveAttrValus(scope)
            }
        },
        async saveAttrValus(scope){
            const {data:res} = await this.$http.put(`categories/${this.catId}/attributes/${scope.row.attr_id}`,{
                    attr_name:scope.row.attr_name,
                    attr_sel:scope.row.attr_sel,
                    attr_vals:scope.row.attr_vals.join(' ')
                });
                if(res.meta.status == 200){
                    this.$message.success(res.meta.msg);
                }else{
                    this.$message.error(res.meta.msg);
                }
        },
        showInput(scope){
            scope.row.inputVisible = true;
            this.$nextTick(_=>{
                this.$refs.saveTagInput.$refs.input.focus();
            })
        },
        handleClose(index,scope){
            console.log(scope);
            scope.row.attr_vals.splice(index,1)
            this.saveAttrValus(scope)
        }
    }
}
</script>
<style lang="less" scoped>
.cat_opt {
    margin-top: 10px;
}

.el-tag {
    margin: 5px;
}

.el-tag:nth-child(1){
    margin-left: 30px;
}
.input-new-tag {
    width: 120px;
}
</style>